//
//  OrderInfoViewController.m
//  HTP
//
//  Created by 王鑫 on 15/11/2.
//  Copyright © 2015年 nit. All rights reserved.
//

#import "PayOffOrderInfoViewController.h"

#import <AlipaySDK/AlipaySDK.h>
#import "Order.h"
#import "DataSigner.h"


@interface PayOffOrderInfoViewController ()

@property (nonatomic,retain) UIScrollView *backView;

@property (nonatomic, retain) UIImageView *topTextImage;

@property (nonatomic, retain) UIImageView *topIcoImage;

@property (nonatomic, retain) UIImageView *topVIew;

@property (nonatomic, retain) UILabel *orderIDLabel;

@property (nonatomic, retain) UILabel *teacherNameLabel;

@property (nonatomic, retain) UILabel *priceLabel;

@property (nonatomic, retain) UILabel *teachNumberLabel;

@property (nonatomic, retain) UILabel *creatTimeLabel;

@property (nonatomic, retain) UILabel *moneyLabel;

@property (nonatomic, retain) UILabel *payTimeLabel;

@property (nonatomic, retain) UIButton *alipayButton;

@property (nonatomic, retain) UIButton *balanceButton;

@property (nonatomic, retain) UIButton *payButton;

@property (nonatomic, retain) NSArray *myOderArray;

@property (nonatomic, retain) MyOrderModel *myOrderM;

@property (nonatomic,assign) NSInteger payFlag;//1支付宝 2账户余额
@end

@implementation PayOffOrderInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    [self getMyOrderDetail];
    _payFlag = 1;
    // Do any additional setup after loading the view.
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self addCustomBackBase];
    [self addCustomTitleWithTitle:@"订单详情"];
}

//TODO:UI绘制 -- wangxin
- (void)initUI{
    _backView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeihgt - NavHe)];
    [self.view addSubview:_backView];
    
    _topVIew = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 130)];
    _topVIew.image = [UIImage imageNamed:@"fukuanbg"];
    [self.backView addSubview:self.topVIew];
    
    _topTextImage = [[UIImageView alloc] initWithFrame:CGRectMake(55, 50, 110, 40)];
    [_topVIew addSubview:self.topTextImage];
    
    _topIcoImage = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenWidth - 110, 10, 70, 110)];
    [_topVIew addSubview:self.topIcoImage];
    
    UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 130, ScreenWidth, 1)];
    line.image = [UIImage imageNamed:@"line"];
    [line setAlpha:0.6];
    [self.backView addSubview:line];
    
    _orderIDLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 150, 240, 25)];
    _orderIDLabel.font = [UIFont systemFontOfSize:16.0f];
    [self.backView addSubview:self.orderIDLabel];
    
    _teacherNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 180, 240, 25)];
    _teacherNameLabel.font = [UIFont systemFontOfSize:16.0f];
    [self.backView addSubview:self.teacherNameLabel];
    
    _priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 210, 240, 25)];
    _priceLabel.font = [UIFont systemFontOfSize:16.0f];
    [self.backView addSubview:self.priceLabel];
    
    _teachNumberLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 240, 240, 25)];
    _teachNumberLabel.font = [UIFont systemFontOfSize:16.0f];
    [self.backView addSubview:self.teachNumberLabel];
    
    _creatTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 270, 240, 25)];
    _creatTimeLabel.font = [UIFont systemFontOfSize:16.0f];
    [self.backView addSubview:self.creatTimeLabel];
    
    _moneyLabel = [self getNormolLabel];
    [_moneyLabel setFrame:CGRectMake(0, 400, 470, 30)];
    [_moneyLabel setFont:[UIFont systemFontOfSize:20]];
    [self.backView addSubview:self.moneyLabel];
    
    _payTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 300, 240, 25)];
    _payTimeLabel.font = [UIFont systemFontOfSize:16.0f];
}

//TODO:支付类型按钮样式设置 -- wangxin
- (void)setButtonIcoImage:(NSString *)image ofText:(NSString *)text button:(UIButton *)button {
    
    [button.layer setBorderWidth:1];
    [button.layer setBorderColor:[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:0.6].CGColor];
    [button setBackgroundImage:[UIImage imageNamed:@"zhuangtaibg"] forState:UIControlStateSelected];
    
    if ([image isEqualToString:@"selfPay"]) {
        [button addTarget:self action:@selector(balanceButtonDown) forControlEvents:UIControlEventTouchUpInside];
    }else{
        [button addTarget:self action:@selector(alipayButtonDown) forControlEvents:UIControlEventTouchUpInside];
    }
    

    UIImageView *icoImage = [[UIImageView alloc] initWithFrame:CGRectMake(35, 5, 30, 30)];
    icoImage.image = [UIImage imageNamed:image];
    [button addSubview:icoImage];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 10, 90, 20)];
    label.text = text;
    [button addSubview:label];
}

//TODO:支付按钮2选1的实现 --wangxin
- (void)alipayButtonDown {
    _payFlag = 1;
    _alipayButton.selected = true;
    _balanceButton.selected = false;
}

- (void)balanceButtonDown {
    _payFlag = 2;
    _alipayButton.selected = false;
    _balanceButton.selected = true;
}

//数据获取
- (void)getMyOrderDetail {
    MyOrderViewModel *myOderVM = [[MyOrderViewModel alloc] init];
    [myOderVM setBlockWithReturnBlock:^(id returnValue) {
        [self hiddenMbProgress];
        [self getData:(NSDictionary *)returnValue];
        [self setData];
    } WithErrorBlock:^(id errorCode) {
        [self hiddenMbProgress];
    } WithFailureBlock:^{
        [self hiddenMbProgress];
    }];
    [self showMbProgress:@""];
    [myOderVM getOrderDetailByOrderId:_orderID];
}

//字典 - 》 模型
- (void)getData:(NSDictionary *)message {
    _myOrderM = [MyOrderModel mj_objectWithKeyValues:message[INTERFACE_INFO]];
}


//数据设置
- (void)setData {
    
    _payTimeLabel.text     = [NSString stringWithFormat:@"付款时间:%@",_myOrderM.ordTime];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"￥%.2lf",[_myOrderM.ordValue floatValue]]];
    NSInteger length = [NSString stringWithFormat:@"￥%.2lf",[_myOrderM.ordValue floatValue]].length;
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(1, 1)];
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:NSMakeRange(1, length - 3)];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(1, length - 1)];
    _moneyLabel.attributedText = str;
    
    _creatTimeLabel.text   = [NSString stringWithFormat:@"创建时间:%@",_myOrderM.ordCreatTime];
    _teachNumberLabel.text = [NSString stringWithFormat:@"上课次数:%@",_myOrderM.ordCourseTime];
    _priceLabel.text       = [NSString stringWithFormat:@"单价:%@元/h",_myOrderM.ordSinglePrice];
    _teacherNameLabel.text = [NSString stringWithFormat:@"教师:%@",_myOrderM.teacherName];
    _orderIDLabel.text     = [NSString stringWithFormat:@"订单编号:%@",_myOrderM.ordCode];
    
    _topTextImage.image = [UIImage imageNamed:@"wifukuan"];
    _topIcoImage.image = [UIImage imageNamed:@"wenhao"];

    

    _alipayButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 310, ScreenWidth, 40)];
    _alipayButton.selected = true;
    [self setButtonIcoImage:@"alipay" ofText:@"支付宝付款" button:_alipayButton];
    [self.backView addSubview:self.alipayButton];
    
    _balanceButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 350, ScreenWidth, 40)];
    [self setButtonIcoImage:@"selfPay" ofText:@"余额支付" button:_balanceButton];
    [self.backView addSubview:self.balanceButton];
    
    _payButton = [[UIButton alloc] initWithFrame:CGRectMake((ScreenWidth - 280) / 2.0, 440, 280, 35)];
    _payButton.backgroundColor = [UIColor colorWithRed:83 / 255.0 green:216 / 255.0 blue:22 / 255.0 alpha:1];
    _payButton.layer.cornerRadius = 7.0;
    _payButton.titleLabel.font = [UIFont systemFontOfSize:20.0f];
    [_payButton setTitle:@"去付款" forState:UIControlStateNormal];
    [_payButton addTarget:self action:@selector(payAction) forControlEvents:UIControlEventTouchUpInside];
    [self.backView addSubview:self.payButton];
    
    [self.backView setContentSize:CGSizeMake(ScreenWidth, CGRectGetMaxY(_payButton.frame)+20)];

}
//TODO:Action
-(void)payAction{
    if (_payFlag == 1) {
        [self alipayAction];
    }else{
        [self showSVProgressFailed:@"账户余额不足"];
    }
}

//TODO:支付宝相关
-(void)alipayAction{
    NSString *partner = m_ALIPAY_partner;
    NSString *seller = m_ALIPAY_seller;
    NSString *privateKey = m_ALIPAY_privateKey;
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.seller = seller;
    order.tradeNO = _myOrderM.ordCode; //订单ID（由商家自行制定）
    order.productName = @"青苗家教"; //商品标题
    double price = [_myOrderM.ordValue doubleValue];
    order.productDescription = [NSString stringWithFormat:@"%@(*%@)",_myOrderM.courseName,_myOrderM.ordCourseTime]; //商品描述
    order.amount = [NSString stringWithFormat:@"%.2f",price]; //商品价格
        order.notifyURL =  @"http://t.xuebaeasy.com:8080/aliPayNotifyUrl.jsp"; //回调URL
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"HTPSchemes";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            [self alipayResultAction:resultDic];
        }];
        
    }

}
-(void)alipayResultAction:(NSDictionary *)resultDic{
    NSString *stringResult = [NSString stringWithFormat:@"%@",[resultDic objectForKey:@"resultStatus"]];
    if ([stringResult isEqualToString:@"9000"]) {
        [self changeOrderStatu];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付宝支付结果" message:@"支付成功" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert showAlertViewWithCompleteBlock:^(NSInteger buttonIndex) {
            [[NSNotificationCenter defaultCenter] postNotificationName:MyFormToFinish object:nil];
            [self backToQM];
        }];
    }else{
        NSString *erString = [NSString stringWithFormat:@"支付失败!请重试或者联系客服!"];
        if ([stringResult isEqualToString:@"6001"]) {
            erString = [NSString stringWithFormat:@"用户中途取消"];
        }else if([stringResult isEqualToString:@"6002"]) {
            erString = [NSString stringWithFormat:@"网络连接出错"];
        }
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付宝支付结果" message:erString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        alert.delegate = self;
        [alert show];
    }
}
//TODO:订单完成修改本地订单状态
-(void)changeOrderStatu{
    OrderData *order = [OrderData findFirstByAttribute:@"ordId" withValue:_myOrderM.ordId];
    if (order == nil) {
        return;
    }
    order.ordStatus = @(2);
    [XLCoreDataManager save];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
